package com.myy.common.exception;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(Exception ex) {
        String message = getParameterExceptionMessage(ex);
        if (StrUtil.isNotBlank(message)) {
            return ResponseEntity.badRequest().body(message);
        } else if (ex instanceof MethodArgumentNotValidException) {
            Map<String, String> errs = new HashMap<>();
            ((MethodArgumentNotValidException) ex).getBindingResult().getAllErrors()
                    .forEach(err -> errs.put(StrUtil.toString(ReflectUtil.getFieldValue(err, "field")), err.getDefaultMessage()));
            return ResponseEntity.badRequest().body(errs);
        } else {
            log.error("程序运行错误", ex);
            return ResponseEntity.badRequest().body(ExceptionUtil.stacktraceToString(ex));
        }
    }

    private String getParameterExceptionMessage(Throwable ex) {
        if (ex == null) {
            return null;
        }
        if (ex instanceof ParamException) {
            return ex.getMessage();
        } else {
            return getParameterExceptionMessage(ex.getCause());
        }
    }

}
